package com.chaoxuan.uebt.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;

import com.chaoxuan.uebt.R;
import com.chaoxuan.uebt.fragment.FindFragment;
import com.chaoxuan.uebt.fragment.IndexFragment;
import com.chaoxuan.uebt.fragment.InfoFragment;
import com.chaoxuan.uebt.fragment.UserFragment;
import com.chaoxuan.uebt.fragment.WelcomeFragment;
import com.chaoxuan.uebt.model.Update;
import com.chaoxuan.uebt.model.User;
import com.chaoxuan.uebt.utils.ActivityUtils;
import com.chaoxuan.uebt.utils.BaseSubscriber;
import com.chaoxuan.uebt.utils.CacheUtils;
import com.chaoxuan.uebt.utils.Const;
import com.chaoxuan.uebt.utils.ICallBack;
import com.chaoxuan.uebt.utils.RetrofitUtils;
import com.chaoxuan.uebt.utils.SavePhoto;
import com.chaoxuan.uebt.utils.ToastUtils;
import java.net.URI;


public class MainActivity extends BaseActivity implements View.OnClickListener,ICallBack {

    private Fragment currentFragment,welcomeFragment,indexFragment,findFragment,userFragment,infoFragment;
    private View btn1,btn2,btn3,btn4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1=findViewById(R.id.btn1);
        btn1.setOnClickListener(this);
        btn2=findViewById(R.id.btn2);
        btn2.setOnClickListener(this);
        btn3=findViewById(R.id.btn3);
        btn3.setOnClickListener(this);
        btn4=findViewById(R.id.btn4);
        btn4.setOnClickListener(this);
        btn1.setSelected(true);
        index();
        load();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn1:
                index();
                break;
            case R.id.btn2:
                find();
                break;
            case R.id.btn3:
                news();
                break;
            case R.id.btn4:
                user();
                break;
        }
    }

    private void index(){
        btn1.setSelected(true);
        btn2.setSelected(false);
        btn3.setSelected(false);
        btn4.setSelected(false);
        User user= CacheUtils.getInstance(this).getUser();
        if(user==null){
            if(welcomeFragment==null)welcomeFragment=new WelcomeFragment();
            switchFragment(welcomeFragment).commit();
        }else{
            if(indexFragment==null){
                indexFragment=new IndexFragment();
                ((IndexFragment) indexFragment).setCallBack(this);
            }
            switchFragment(indexFragment).commit();
        }
    }
    private void find(){
        btn1.setSelected(false);
        btn2.setSelected(true);
        btn3.setSelected(false);
        btn4.setSelected(false);
        if(findFragment==null)findFragment=new FindFragment();
        switchFragment(findFragment).commit();
    }
    private void news(){
        btn1.setSelected(false);
        btn2.setSelected(false);
        btn3.setSelected(true);
        btn4.setSelected(false);
        if(infoFragment==null)infoFragment=new InfoFragment();
        switchFragment(infoFragment).commit();
    }
    private void user(){
        User user=CacheUtils.getInstance(this).getUser();
        if(user==null){
            startActivity(new Intent(this,LoginActivity.class));
            return;
        }
        btn1.setSelected(false);
        btn2.setSelected(false);
        btn3.setSelected(false);
        btn4.setSelected(true);
        if(userFragment==null) {
            userFragment = new UserFragment();
            ((UserFragment) userFragment).setCallBack(this);
        }
        switchFragment(userFragment).commit();
    }

    private FragmentTransaction switchFragment(Fragment targetFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
             if (currentFragment != null) {
                 transaction.hide(currentFragment);
             }
            transaction.add(R.id.fragment, targetFragment,targetFragment.getClass().getName());
        } else {
            transaction.hide(currentFragment).show(targetFragment);
        }
        currentFragment = targetFragment;
        return transaction;
    }

    private EmptyClient client=null;

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("---","index1");
        dig();
        if(Const.TAB==-1)return;
        else if(Const.TAB==1)index();
        else if(Const.TAB==4)user();
        Const.TAB=-1;

    }

    @Override
    public void onChange(String message,boolean close) {
        Log.d("=======onChange=======",message);
        if(indexFragment!=null&&(indexFragment instanceof IndexFragment)){
            ((IndexFragment)indexFragment).show(message,close);
        }
        if(close)logout();
    }

    @Override
    public void dig() {
        try {
            User user=CacheUtils.getInstance(this).getUser();
            Log.d("=======start=======","--");
            if(user!=null&&client==null) {
                Log.d("=======start=======","start");
                client= new EmptyClient(new URI("ws://47.75.188.220:2345"), user.getToken(),this);
                client.connect();
            }else if(user==null&&client!=null){
                client.stop();
                client=null;
            }
        }catch (Exception e){
            Log.d("====",e.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //logout();
    }

    @Override
    public void logout() {
        Log.d("====LOOUT====","true");
        if(client!=null){
            client.stop();
            client=null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    saveQrcode();
                }
                break;
            }
        }
    }
    Bitmap img;
    @Override
    public void saveQrcode(Bitmap bitmap) {
        img=bitmap;
        saveQrcode();
    }

    private  void saveQrcode(){
        try {
            String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}; //检测是否有写的权限
            int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission != PackageManager.PERMISSION_GRANTED) {// 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
            } else {
                SavePhoto savePhoto = new SavePhoto(this);//创建savephoto类保存图片
                savePhoto.saveBitmap(img, img.toString() + ".JPEG");
                ToastUtils.showCustomToast("保存成功");
            }
        }catch (Exception e){
            Log.e("====",e.getMessage());
        }
    }

    private void load(){
        subscribe(RetrofitUtils.getAPIService().version(), new BaseSubscriber<Update>() {
            @Override
            public void onSuccess(Update update) {
                int code=ActivityUtils.getVersionCode(getBaseContext());
                Log.d("==========",code+"---"+update.getUpdate());
                if(update.getUpdate()>code){
                    show(update.getApk_file_url());
                }
            }
        });
    }
    private void show(final String apkUrl){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);//内部类
        builder.setTitle("提示");
        builder.setMessage("有版本更新?");
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
               download(apkUrl);
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    private void download(String apkUrl){
        ActivityUtils.download(this,apkUrl);
    }
}
